package com.shen.lock;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;


public class SpinlockDemo {
    AtomicReference atomicReference=new AtomicReference<Thread>();//CAS操作线程对象

    /**
     * 加锁
     */
    public void  lock(){
        Thread thread = Thread.currentThread();
        System.out.println(thread.getName()+" ====> 开始上锁");

        //自旋锁 一直判断是否是null
        while (!atomicReference.compareAndSet(null,thread)){

        }
    }

    /**
     * 解锁
     */
    public void unlock(){
        Thread thread = Thread.currentThread();
        System.out.println(thread.getName()+" ====> 开始解锁");
        atomicReference.compareAndSet(thread,null);
    }


    public static void main(String[] args) {
        SpinlockDemo lock=new SpinlockDemo();
        new Thread(()->{
            lock.lock();//加锁
            try {
                System.out.println(Thread.currentThread().getName()+"已加锁");
                TimeUnit.SECONDS.sleep(2);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                lock.unlock();//解锁
                System.out.println(Thread.currentThread().getName()+"已解锁");
            }

        },"T1").start();

        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        new Thread(()->{
            lock.lock();//加锁
            try {
                System.out.println(Thread.currentThread().getName()+"==已加锁");
                TimeUnit.SECONDS.sleep(2);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                lock.unlock();//解锁
                System.out.println(Thread.currentThread().getName()+"已解锁");
            }
        },"T2").start();

        /**
         * T1 ====> 开始上锁
         * T1已加锁
         * T2 ====> 开始上锁    这里T1已上锁，T2在自旋，等T1解锁后再上锁
         * T1 ====> 开始解锁
         * T1已解锁            这里T1已解锁，T2上锁
         * T2已加锁            T2上锁成功
         * T2 ====> 开始解锁
         * T2已解锁
         */


    }
}
